<template>
  <div class="cell_style">
    <div class="my-cell" @click="showTree">
      <div class="my-cell-title">
        <span class="weui-label" style="width:100px;font-size:14px">{{title}}</span>
      </div>
      <div class="my-cell-content">
        <tag v-for="(item,index) in checked" :key="index" @click="deleteCheck" :value="item" :closable="!readonly">
        </tag>
      </div>
      <!-- <div class="icon"></div> -->
      <!-- <div class="my-cell-icon"  v-if="!readonly">
        <icon name="plus" class="default-icon"></icon>
      </div> -->
    </div>
    <div v-transfer-dom class="self-tree">
      <popup v-model="show" height="100%" :hide-on-blur="false" @on-hide="closeMask"
        :popup-style="{'z-index':9998,'overflow': 'hidden'}">
        <popup-header right-text="确定" title="人员选择" :show-bottom-border="false" @on-click-right="check"></popup-header>
        <simple-search @onClear="onClear" @onSearch="onSearch" placeholder="请输入人员" ref="edit"></simple-search>
        <!--选人控件新增项目过滤 by  江培   开始-->
        <!-- <group>
          <popup-picker title="项目"
                        :data="prjList"
                        v-model="selectedPrj"
                        placeholder="项目群层"
                        popup-title="项目选择"
                        :popup-style="{'z-index':9999,'overflow': 'hidden','height':'100%'}"
                        @on-change="listDeptByPrjId"
                        show-name></popup-picker>
        </group> -->
        <!--选人控件新增项目过滤 by  江培   结束-->
        <!-- 修改项目过滤 by 毛程隆 开始 -->
        <choose-project title="项目选择" @selected="selectProject"></choose-project>
        <!-- 修改项目过滤 by 毛程隆 结束 -->
        <div class="after-search" style=" height:calc(100% - 90px)">
          <tree-root :list="isSearch?list:tree" :value="checked" :checkbox="true" :loadData="true"
            :usernames="usernames" name="NAME" children="children" ref="tree" :type="isSearch?'person':'dept'"
            :multiple="multiple" :prjId='selectedPrjNew !=="" ?selectedPrjNew:"0"' @selectUser='selectUser'
            @flag="getFlag"></tree-root>
        </div>

      </popup>
    </div>
  </div>
</template>

<script>
  import TreeRoot from "./treeRoot";
  import Tag from "../tag/tag";
  import {
    setTimeout
  } from 'timers';
  export default {
    name: "personTree",
    components: {
      Tag,
      TreeRoot
    },
    mounted() {
      if (this.defaultValue != "") {
        this.onLocate(this.defaultValue)
      }
    },
    props: {
      value: {
        type: String,
        default () {
          return ""
        }
      },
      //person 人员/dept  部门
      type: {
        type: String,
        default () {
          return 'person'
        }
      },
      title: {
        type: String,
        default: ""
      },
      multiple: {
        type: Boolean,
        default () {
          return false
        }
      },
      readonly: {
        type: Boolean,
        default () {
          return false
        }
      },
      personid: {
        type: String,
        default () {
          return ""
        }
      },
      defaultValue: {
        type: String,
        default () {
          return ""
        }
      }
    },
    data() {
      return {
        show: false,
        isSearch: false,
        list: [],
        prjList: [],
        selectedPrj: [],
        selectedPrjNew: "",
        tree: this.$store.state.deptTree,
        flag: false
      }
    },
    methods: {
      getFlag(val) {
        this.flag = val
      },
      selectProject(val) {
        this.selectedPrjNew = val.value
        this.onClear()
        this.$refs.edit.clear()
        console.log(this.selectedPrjNew)
      },
      // onSwipeRight(){
      //    this.$router.go(-1)
      // },
      selectUser(val) {
        this.$emit('selectUser', val)
      },
      /**
       * 获取项目列表，用于进行人员选择过滤
       */
      listPrj() {
        if (this.checkNetWork()) {
          this.$ajax({
            url: this.COMMON_URL + '?_method=V_USER_SELECT*getProjectList',
            method: 'post',
            data: {
              pageIndex: '0',
              pageSize: '1000',
              sortField: '',
              sortOrder: ''
            }
          }).then(res => {
            // console.log("部门列表",res);
            this.prjList = res.data.treedata.map(item => {
              return {
                name: item.NAME,
                value: item.ID
              }
            })
            this.prjList.unshift({
              name: '项目群层',
              value: '0'
            })
            this.prjList = [this.prjList]
          })
        } else {
          this.$store.state.SQLiteDB.transaction(tx => {
            tx.executeSql('select * from SYS_PROJECTINFO where PROJECTID != "0"', [], (tx, result) => {
              var temp = []
              for (var i = 0; i < result.rows.length; i++) {
                temp[i] = result.rows.item(i);
              }

              this.prjList = temp.map(item => {
                return {
                  name: item.PROJECTNAME,
                  value: item.PROJECTID
                }
              })
              this.prjList.unshift({
                name: '项目群层',
                value: '0'
              })
              this.prjList = [this.prjList]
            })
          })
        }

      },
      /**
       * 根据项目id查找部门，保证能够选到项目级的人员
       */
      listDeptByPrjId() {
        // let prjId = this.selectedPrj ? this.selectedPrj[0] : 0
        var prjId = this.selectedPrjNew !== "" ? this.selectedPrjNew : '0'
        if (this.checkNetWork()) {
          this.$ajax({
            url: this.COMMON_URL, //+ '?_method=V_USER_SELECT*getHRGroupTreeList&type=prj&projectId=' + prjId,
            method: 'post',
            data: {
              _method: "V_USER_SELECT*getHRGroupTreeList",
              type: "prj",
              projectId: prjId,
              pageIndex: '0',
              pageSize: '1000',
              sortField: '',
              sortOrder: ''
            }
          }).then(res => {
            this.tree = this.toTree(res.data.treedata)
          })
        } else {
          this.$store.state.SQLiteDB.transaction((tx) => {
            tx.executeSql(
              'SELECT ID,NAME,ORG_PATHID,ORG_PATHNAME,PARENTID FROM V_FIX_GROUP WHERE ORG_PATHID IS NOT NULL AND PARENTID <> "0" AND PRJID = "' +
              prjId + '" ORDER BY FLOORID', [], (tx, result) => {
                var temp = [];
                for (var i = 0; i < result.rows.length; i++) {
                  temp[i] = result.rows.item(i);
                }
                this.tree = this.toTree(temp);
              })
          }, (err) => {
            console.log('错误', err)
          })
        }


      },
      showTree() {
        if (this.readonly)
          return false
        this.show = true,
          // this.listPrj(),
          this.$store.commit("CHANGE_DEFAULT_POPUP")
      },
      //选择按钮
      check() {
        //cordova.plugins.Keyboard.close();
        this.$emit('input', this.checked.join(","))
        this.show = false;
      },
      deleteCheck(val) {
        this.checked.splice(this.checked.findIndex(item => item === val), 1)
        this.$emit('input', this.checked.join(","))
      },
      onClear() {
        this.isSearch = false;
      },
      //定位默认填充人
      onLocate(val) {
        if (!val) {
          this.isSearch = false;
          return false;
        }
        // var prjId = this.selectedPrj.length !== 0 ? this.selectedPrj[0] : '0'
        var prjId = this.selectedPrjNew !== "" ? this.selectedPrjNew : '0'
        this.locatePerson(val, 'chooseuser', prjId, (res) => {

          var searchData = []
          if (this.checkNetWork()) {
            searchData = res.data.data
          } else {
            //执行离线状态时的任务   
            searchData = res
          }
          if (searchData) {
            this.list = searchData;
            this.list.forEach((item) => {
              item.showContent = true;
              item.showContent1 = true;
              item.showContent2 = true;
            });
            this.isSearch = true;
          }
        })
      },
      onSearch(val) {
        if (!val) {
          this.isSearch = false;
          return false;
        }
        // var prjId = this.selectedPrj.length !== 0 ? this.selectedPrj[0] : '0'
        var prjId = this.selectedPrjNew !== "" ? this.selectedPrjNew : '0'
        this.getPerson(val, 'chooseuser', prjId, (res) => {

          var searchData = []
          if (this.checkNetWork()) {
            searchData = res.data.data
          } else {
            //执行离线状态时的任务   
            searchData = res
          }
          if (searchData) {
            this.list = searchData;
            this.list.forEach((item) => {
              item.showContent = true;
              item.showContent1 = true;
              item.showContent2 = true;
            });
            this.isSearch = true;
          }
        })

      },
      getValues(val) {
        return this.$refs.tree.getValues(val)
      }
    },
    computed: {

      checked() {
        return this.value ? this.value.split(',') : []
      },
      usernames() {
        return this.personid ? this.personid.split(',') : []
      }
    },
    watch: {
      "$store.state.defaultPop"() {
        if (!this.$store.state.defaultPop) {
          this.show = false;
        }
      },
      personid: {
        handler(newVal) {
          this.personid = this.personid;
        }
      },
      selectedPrjNew() {
        this.listDeptByPrjId();
      },
      defaultValue: {
        handler(newVal) {
          if (!this.flag) {
            this.onLocate(newVal);
          }
        },
        deep: true
      }
    }
  }

</script>

<style scoped>
  .my-cell {
    -webkit-box-align: center;
    -webkit-align-items: center;
    align-items: center;
    position: relative;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    color: #9f9f9f;
    font-size: 13px;
    left: -15px;
    padding-top: 7px;
    line-height: 40px !important;
    padding: 10px 0;
  }

  .my-cell::after {
    content: " ";
    display: inline-block;
    height: 6px;
    width: 6px;
    border-width: 2px 2px 0 0;
    border-color: #c8c8cd;
    border-style: solid;
    -webkit-transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
    transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
    position: relative;
    top: -2px;
    left: -2px;
  }

  .my-cell-title {
    -webkit-box-flex: 1;
    -webkit-flex: 1;
    flex: 1;
    color: #000000;
    padding-left: 30px;
  }

  .my-cell-content {
    /* width: 100%; */
    position: relative;
    /* padding-right: 35px; */
    /* padding-right: 10%; */
    color: #888888;
  }

  /* .my-cell-icon{
  position: absolute;
  right: 15px;
  text-align: right;
  color: #C8C8CD;
} */
  /* .my-cell-content:after {
  content: " ";
  display: inline-block;
  height: 6px;
  width: 6px;
  border-width: 2px 2px 0 0;
  border-color: #c8c8cd;
  border-style: solid;
  -webkit-transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
  transform: matrix(0.71, 0.71, -0.71, 0.71, 0, 0);
  position: relative;
  top: -2px;
  left: 5px;
} */
  .moa-search-div {
    margin: 0 !important;
    padding: 12px 16px !important;
    width: 100% !important;
    background-color: #4D86FF !important;
    border: none !important;
    border-radius: 0px !important;
  }

  .vux-popup-header /deep/ .vux-popup-header-title {
    color: #ffffff !important;
  }

  .vux-popup-header /deep/ .vux-popup-header-right {
    color: #ffffff !important;
  }

  .vux-popup-header {
    margin: 0 !important;
    width: 100% !important;
    background-color: #4D86FF !important;
    border: none !important;
    border-radius: 0px !important;
  }

</style>
